import Sortable from 'sortablejs'
import { ref } from 'vue'
import { articleSort } from '@/api/article'
import { ElMessage } from 'element-plus'
import i18n from '@/i18n'

export const tableRef = ref(null)
export const initSortable = (articleList, cb) => {
  const el = tableRef.value.$el.querySelectorAll('.el-table__body-wrapper table > tbody')[0]

  // 1. 要拖拽的对象
  // 2. 配置对象
  Sortable.create(el, {
    // 拖拽时的类名
    ghostClass: 'sortable-ghost',
    // 拖拽结束的回调
    async onEnd (event) {
      const { oldIndex, newIndex } = event
      await articleSort({
        initRanking: articleList.value[oldIndex].ranking,
        finalRanking: articleList.value[newIndex].ranking
      })
      ElMessage.success(i18n.global.t('msg.article.sortSuccess'))
      articleList.value = []
      cb && cb()
    }
  })
}